<script setup lang="ts">
import { ref, reactive, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 登录类型
type LoginType = 'password' | 'sms';

// 响应式数据
const loginType = ref<LoginType>('password');
const isLoading = ref(false);
const isPasswordVisible = ref(false);
const rememberPassword = ref(false);
const autoLogin = ref(false);
const smsCountdown = ref(0);
let smsTimer: number | null = null;

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  phone: '',
  smsCode: ''
});

// 消息状态
const message = reactive({
  type: null as 'error' | 'success' | null,
  text: ''
});

// 切换登录类型
const handleSwitchLoginType = (type: LoginType) => {
  loginType.value = type;
  hideMessage();
};

// 切换密码可见性
const handleTogglePasswordVisibility = () => {
  isPasswordVisible.value = !isPasswordVisible.value;
};

// 显示消息
const showMessage = (type: 'error' | 'success', text: string) => {
  message.type = type;
  message.text = text;
  const timeout = type === 'error' ? 5000 : 3000;
  setTimeout(hideMessage, timeout);
};

// 隐藏消息
const hideMessage = () => {
  message.type = null;
  message.text = '';
};

// 手机号验证
const validatePhone = (phone: string): boolean => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 开始验证码倒计时
const startSmsCountdown = () => {
  smsCountdown.value = 60;
  
  if (smsTimer) {
    clearInterval(smsTimer);
  }
  
  smsTimer = setInterval(() => {
    smsCountdown.value--;
    if (smsCountdown.value <= 0) {
      if (smsTimer) {
        clearInterval(smsTimer);
      }
    }
  }, 1000);
};

// 获取验证码
const handleGetSmsCode = () => {
  if (!formData.phone) {
    showMessage('error', '请先输入手机号');
    return;
  }
  
  if (!validatePhone(formData.phone)) {
    showMessage('error', '请输入正确的手机号');
    return;
  }
  
  // 开始倒计时
  startSmsCountdown();
  showMessage('success', '验证码已发送');
};

// 处理密码登录
const handlePasswordLogin = async () => {
  if (!formData.username || !formData.password) {
    showMessage('error', '请填写完整的登录信息');
    return;
  }
  
  isLoading.value = true;
  hideMessage();
  
  try {
    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 存储登录状态
    localStorage.setItem('isAuthenticated', 'true');
    if (rememberPassword.value) {
      localStorage.setItem('rememberedUsername', formData.username);
    }
    
    // 登录成功，跳转到首页
    router.push('/');
  } catch (error) {
    showMessage('error', '登录失败，请检查用户名和密码');
  } finally {
    isLoading.value = false;
  }
};

// 处理验证码登录
const handleSmsLogin = async () => {
  if (!formData.phone || !formData.smsCode) {
    showMessage('error', '请填写完整的登录信息');
    return;
  }
  
  if (!validatePhone(formData.phone)) {
    showMessage('error', '请输入正确的手机号');
    return;
  }
  
  isLoading.value = true;
  hideMessage();
  
  try {
    // 模拟登录请求
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 存储登录状态
    localStorage.setItem('isAuthenticated', 'true');
    
    // 登录成功，跳转到首页
    router.push('/');
  } catch (error) {
    showMessage('error', '登录失败，请检查验证码');
  } finally {
    isLoading.value = false;
  }
};

// 处理登录
const handleLogin = () => {
  if (isLoading.value) return;
  
  if (loginType.value === 'password') {
    handlePasswordLogin();
  } else {
    handleSmsLogin();
  }
};

// 忘记密码
const handleForgotPassword = () => {
  showMessage('error', '请联系管理员重置密码');
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (smsTimer) {
    clearInterval(smsTimer);
  }
});
</script>

<template>
  <div class="login-container">
    <div class="login-content">
      <!-- 顶部Logo区域 -->
      <div class="logo-header">
        <div class="logo-container">
          <div class="app-logo">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"></path>
              <path d="m3.34 16 8.66-2.5"/>
              <path d="m20.66 8-8.66 2.5"/>
            </svg>
          </div>
          <h1 class="app-name">流批通</h1>
          <p class="app-slogan">高效移动审批平台</p>
        </div>
      </div>
      
      <!-- 登录表单区域 -->
      <div class="login-main">
        <div class="login-card">
          <!-- 登录方式切换 -->
          <div class="login-type-switch">
            <button
              class="switch-tab"
              :class="{ active: loginType === 'password' }"
              @click="handleSwitchLoginType('password')"
            >
              账号密码登录
            </button>
            <button
              class="switch-tab"
              :class="{ active: loginType === 'sms' }"
              @click="handleSwitchLoginType('sms')"
            >
              验证码登录
            </button>
          </div>
          
          <!-- 账号密码登录表单 -->
          <div v-if="loginType === 'password'" class="form-container">
            <div class="input-group">
              <label class="input-label">用户名</label>
              <div class="input-wrapper">
                <input
                  type="text"
                  class="text-input"
                  placeholder="请输入用户名"
                  v-model="formData.username"
                  @input="hideMessage"
                  autocomplete="username"
                />
                <svg class="input-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
              </div>
            </div>
            
            <div class="input-group">
              <label class="input-label">密码</label>
              <div class="input-wrapper">
                <input
                  :type="isPasswordVisible ? 'text' : 'password'"
                  class="text-input"
                  placeholder="请输入密码"
                  v-model="formData.password"
                  @input="hideMessage"
                  autocomplete="current-password"
                />
                <button class="password-toggle-button" @click="handleTogglePasswordVisibility">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <template v-if="isPasswordVisible">
                      <path d="M3 9a9 9 0 0 1 18 0"></path>
                      <path d="M21 12a9 9 0 0 1-18 0"></path>
                      <line x1="12" y1="3" x2="12" y2="21"></line>
                    </template>
                    <template v-else>
                      <path d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"></path>
                      <path d="M2.93 19a10.05 10.05 0 0 1 18.14 0"></path>
                      <path d="M1.39 11a16 16 0 0 1 21.22 0"></path>
                      <path d="M8 14s1.5 2 4 2 4-2 4-2"></path>
                    </template>
                  </svg>
                </button>
              </div>
            </div>
            
            <!-- 记住密码和自动登录 -->
            <div class="login-options">
              <label class="checkbox-container">
                <input type="checkbox" v-model="rememberPassword" />
                <span class="checkmark"></span>
                <span class="checkbox-label">记住密码</span>
              </label>
              
              <label class="checkbox-container">
                <input type="checkbox" v-model="autoLogin" />
                <span class="checkmark"></span>
                <span class="checkbox-label">自动登录</span>
              </label>
            </div>
          </div>
          
          <!-- 验证码登录表单 -->
          <div v-if="loginType === 'sms'" class="form-container">
            <div class="input-group">
              <label class="input-label">手机号</label>
              <div class="input-wrapper">
                <input
                  type="tel"
                  class="text-input"
                  placeholder="请输入手机号"
                  v-model="formData.phone"
                  @input="hideMessage"
                  maxlength="11"
                  autocomplete="tel"
                />
                <svg class="input-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="5" y="2" width="14" height="20" rx="2" ry="2"></rect>
                  <line x1="12" y1="18" x2="12.01" y2="18"></line>
                </svg>
              </div>
            </div>
            
            <div class="input-group">
              <label class="input-label">验证码</label>
              <div class="sms-input-wrapper">
                <input
                  type="text"
                  class="sms-input"
                  placeholder="请输入验证码"
                  v-model="formData.smsCode"
                  @input="hideMessage"
                  maxlength="6"
                  autocomplete="one-time-code"
                />
                <button
                  class="get-sms-code-button"
                  :disabled="smsCountdown > 0"
                  @click="handleGetSmsCode"
                >
                  {{ smsCountdown > 0 ? `${smsCountdown}秒后重发` : '获取验证码' }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 错误/成功提示 -->
          <div v-if="message.type" class="message-container">
            <div class="message" :class="message.type === 'error' ? 'error' : 'success'">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <line v-if="message.type === 'error'" x1="12" y1="8" x2="12" y2="12"></line>
                <line v-if="message.type === 'error'" x1="12" y1="16" x2="12.01" y2="16"></line>
                <path v-if="message.type === 'success'" d="m9 12 2 2 4-4"></path>
              </svg>
              <span class="message-text">{{ message.text }}</span>
            </div>
          </div>
          
          <!-- 登录按钮 -->
          <button
            class="login-button"
            :disabled="isLoading"
            @click="handleLogin"
          >
            <span>{{ isLoading ? '登录中...' : '登录' }}</span>
            <svg v-if="isLoading" class="loading-spinner" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 12a9 9 0 1 1-6.219-8.56"></path>
            </svg>
          </button>
          
          <!-- 忘记密码 -->
          <div v-if="loginType === 'password'" class="forgot-password-container">
            <button class="forgot-password-text" @click="handleForgotPassword">
              忘记密码？
            </button>
          </div>
        </div>
      </div>
      
      <!-- 底部版权信息 -->
      <div class="footer">
        <p class="copyright-text">© 2024 流批通科技有限公司</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.login-content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 顶部Logo区域 */
.logo-header {
  background: linear-gradient(135deg, #969FFF, #5147FF, #3E3987);
  padding: 40px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.app-logo {
  width: 64px;
  height: 64px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.app-name {
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.app-slogan {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

/* 登录表单区域 */
.login-main {
  flex: 1;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 登录方式切换 */
.login-type-switch {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #E5E7EB;
}

.switch-tab {
  padding: 0 8px 12px;
  border: none;
  background: none;
  font-size: 16px;
  font-weight: 500;
  color: #6B7280;
  cursor: pointer;
  position: relative;
  transition: color 0.3s;
}

.switch-tab.active {
  color: #969FFF;
}

.switch-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 8px;
  right: 8px;
  height: 2px;
  background-color: #969FFF;
}

/* 表单样式 */
.form-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.text-input {
  flex: 1;
  height: 48px;
  padding: 0 16px;
  border: 1px solid #D1D5DB;
  border-radius: 8px;
  font-size: 15px;
  color: #1F2937;
  transition: border-color 0.3s;
}

.text-input:focus {
  outline: none;
  border-color: #969FFF;
}

.text-input::placeholder {
  color: #6B7280;
}

.input-icon {
  position: absolute;
  right: 16px;
  color: #6B7280;
}

.password-toggle-button {
  position: absolute;
  right: 16px;
  background: none;
  border: none;
  cursor: pointer;
  color: #6B7280;
  padding: 4px;
}

/* 验证码输入样式 */
.sms-input-wrapper {
  display: flex;
  gap: 12px;
  align-items: center;
}

.sms-input {
  flex: 1;
  height: 48px;
  padding: 0 16px;
  border: 1px solid #D1D5DB;
  border-radius: 8px;
  font-size: 15px;
  color: #1F2937;
}

.sms-input:focus {
  outline: none;
  border-color: #969FFF;
}

.get-sms-code-button {
  height: 48px;
  padding: 0 16px;
  border: 1px solid #969FFF;
  border-radius: 8px;
  background-color: white;
  color: #969FFF;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.get-sms-code-button:hover:not(:disabled) {
  background-color: #969FFF;
  color: white;
}

.get-sms-code-button:disabled {
  border-color: #D1D5DB;
  color: #9CA3AF;
  cursor: not-allowed;
}

/* 登录选项 */
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkbox-container {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-container input {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 1px solid #D1D5DB;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s;
}

.checkbox-container input:checked + .checkmark {
  background-color: #969FFF;
  border-color: #969FFF;
  color: white;
}

.checkbox-container input:checked + .checkmark::after {
  content: '✓';
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.checkbox-label {
  font-size: 14px;
  color: #6B7280;
}

/* 消息提示 */
.message-container {
  margin: 16px 0;
}

.message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
}

.message.error {
  background-color: #FEE2E2;
  color: #B91C1C;
}

.message.success {
  background-color: #D1FAE5;
  color: #166534;
}

.message-icon {
  flex-shrink: 0;
}

.message-text {
  flex: 1;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 48px;
  margin-top: 16px;
  background: linear-gradient(90deg, #969FFF, #5147FF);
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  transition: opacity 0.3s;
}

.login-button:hover:not(:disabled) {
  opacity: 0.9;
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 忘记密码 */
.forgot-password-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.forgot-password-text {
  background: none;
  border: none;
  color: #969FFF;
  font-size: 14px;
  cursor: pointer;
  padding: 4px;
}

/* 底部版权信息 */
.footer {
  padding: 24px;
  text-align: center;
}

.copyright-text {
  font-size: 13px;
  color: #9CA3AF;
  margin: 0;
}
</style>